package redis

import (
	"github.com/BurntSushi/toml"
	"github.com/go-redis/redis/v8"
	"math/rand"
)

type __dbConfigForRedis struct {
	MasterAddress    string   `toml:"master_address"`
	SlaveAddressList []string `toml:"slave_address_list"`
	Database         int      `toml:"database"`
	Password         string   `toml:"pass_word"`
	MaxRetry         int      `toml:"max_retry"`
}

var (
	dbConfigForRedis       = new(__dbConfigForRedis)
	err                    error
	masterRedisClient      *redis.Client
	slaveRedisClient       *redis.Client
	slaveRedisClientList   = make([]*redis.Client, 0)
	slaveRedisClientLength int
)

func SlaveClient() *redis.Client {
	return slaveRedisClientList[rand.Intn(slaveRedisClientLength)]
}

func MasterClient() *redis.Client {
	return masterRedisClient
}

func (d *__dbConfigForRedis) parseConfig(configPath string) error {
	_, err = toml.DecodeFile(configPath, d)
	return err
}
func Init(configPath string) error {
	if err = dbConfigForRedis.parseConfig(configPath); err != nil {
		return err
	}
	masterRedisClient = redis.NewClient(&redis.Options{
		Addr:       dbConfigForRedis.MasterAddress,
		DB:         dbConfigForRedis.Database,
		MaxRetries: dbConfigForRedis.MaxRetry,
		Password:   dbConfigForRedis.Password,
	})
	for _, slaveAddress := range dbConfigForRedis.SlaveAddressList {
		slaveRedisClient = redis.NewClient(&redis.Options{
			Addr:       slaveAddress,
			DB:         dbConfigForRedis.Database,
			MaxRetries: dbConfigForRedis.MaxRetry,
			Password:   dbConfigForRedis.Password,
		})
		slaveRedisClientList = append(slaveRedisClientList, slaveRedisClient)
	}
	slaveRedisClientLength = len(slaveRedisClientList)
	return nil
}

func Exit() {
	_ = masterRedisClient.Close()
	for _, slaveRedisClient := range slaveRedisClientList {
		_ = slaveRedisClient.Close()
	}
}
